package com.ktjiaoyu.ktmall.filter;

import com.alibaba.fastjson.JSON;
import com.ktjiaoyu.ktmall.utils.R;
import com.ktjiaoyu.ktmall.utils.RedisUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@WebFilter("/api/*")
public class TokenFilter implements Filter {
    private static final Set<String> PUBLIC_URIS = new HashSet<>(Arrays.asList(
            "/api/product",
            "/api/category"
    ));
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,FilterChain filterChain)throws IOException,ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setContentType("application/json;charset=UTF-8");
        String opr = "";
        String requestURI = request.getRequestURI();
        for (String publicUri : PUBLIC_URIS) {
            if (requestURI.startsWith(request.getContextPath() + publicUri)) {
                filterChain.doFilter(request, response);
                return;
            }
        }
        if (requestURI.startsWith(request.getContextPath()+"/api/user")){
         opr = request.getParameter("opr");
            if ("login".equals(opr)||"register".equals(opr)){
                filterChain.doFilter(request,response);
                return;
            }
        }
        String userId = RedisUtil.getUserIdFromToken(request);
        if (userId==null){
            PrintWriter out = response.getWriter();
            System.out.println(requestURI+"?opr="+opr+",请求鉴权失败！");
            R result = R.fail().code(401).msg("未登录，请先登录");
            out.print(JSON.toJSONString(result));
            out.flush();
            out.close();
            return;
        }
        RedisUtil.refreshToken(request,1800);
        filterChain.doFilter(request,response);
    }
    @Override
    public void destroy() {}
}
